package com.shujia;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.CellSortReducer;
import org.apache.hadoop.hbase.mapreduce.HFileOutputFormat2;
import org.apache.hadoop.hbase.mapreduce.SimpleTotalOrderPartitioner;
import org.apache.hadoop.hbase.tool.BulkLoadHFiles;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class BulkLoading {
    // Map端
    public static class BulkMapper extends Mapper<LongWritable, Text, ImmutableBytesWritable, KeyValue> {
        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, ImmutableBytesWritable, KeyValue>.Context context) throws IOException, InterruptedException {
            String[] splits = value.toString().split(",");
            String mdn = splits[0]; // 作为RowKey
            String lg = splits[4];
            String lat = splits[5];


            // KeyValue对象 相当于一个Cell
            KeyValue lgKv = new KeyValue(mdn.getBytes(), "cf1".getBytes(), "lg".getBytes(), lg.getBytes());
            KeyValue latKv = new KeyValue(mdn.getBytes(), "cf1".getBytes(), "lat".getBytes(), lat.getBytes());

            context.write(new ImmutableBytesWritable(mdn.getBytes()), lgKv);
            context.write(new ImmutableBytesWritable(mdn.getBytes()), latKv);
        }
    }

    // Reduce端 不需要手动实现 由HBase提供特定的Reduce类 保证数据的全局有序

    // Driver端
    public static void main(String[] args) throws Exception {
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "master,node1,node2");
        conf.set("fs.defaultFS", "hdfs://master:9000");


        Job job = Job.getInstance(conf);
        job.setJobName("Demo08BulkLoading");
        job.setJarByClass(BulkLoading.class);

        // 配置分区类
        // 保证每个Reduce之间是有序的
        job.setPartitionerClass(SimpleTotalOrderPartitioner.class);

        // 配置Map端
        job.setMapperClass(BulkMapper.class);
        job.setMapOutputKeyClass(ImmutableBytesWritable.class);
        job.setMapOutputValueClass(KeyValue.class);

        // 配置Reduce端
        // 保证每个Reduce内的数据是有序的
        job.setReducerClass(CellSortReducer.class);

        // 这个会被MR忽略，Reduce的数量由Region的数量决定的
         job.setNumReduceTasks(3);

        // 配置输入输出路径
        FileInputFormat.addInputPath(job, new Path("hdfs://master:9000/test/bulk/input/"));

        Path path = new Path("hdfs://master:9000/test/bulk/output/");
        FileSystem fs = FileSystem.get(conf);
        if (fs.exists(path)) {
            fs.delete(path, true);
        }

        FileOutputFormat.setOutputPath(job, path);

        Connection conn = ConnectionFactory.createConnection(conf);
        // 首先在HBase中建表：create 'dian_xin_test','cf1',SPLITS => ['3|', '7|', 'B|']
        TableName dianXinName = TableName.valueOf("dian_xin_test");
        Table dian_xin = conn.getTable(dianXinName);
        RegionLocator regionLocator = conn.getRegionLocator(dianXinName);

        // 格式化输出为HFile格式
        HFileOutputFormat2.configureIncrementalLoad(
                job
                , dian_xin
                , regionLocator
        );

        boolean flag = job.waitForCompletion(true);

        if (flag) {
            // 加载HFile到对应的Region中
            System.out.println("正在加载数据");
            BulkLoadHFiles bulkLoadHFiles = BulkLoadHFiles
                    .create(conf);
            bulkLoadHFiles.bulkLoad(dianXinName,path);

        } else {
            System.out.println("未成功加载数据。");
        }

    }
    /*
     * hdfs dfs -mkdir -p /test/bulk/input
     * hdfs dfs -put DIANXIN.csv /test/bulk/input
     * hadoop jar hbase-1.0-jar-with-dependencies.jar com.shujia.hbase.Demo08BulkLoading
     */
}


